package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xuanzheng.company.entity.AIModel;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.AIService;
import com.xuanzheng.company.service.impl.AIServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@WebServlet("/aiModelManagement")
public class AIModelManagementServlet extends HttpServlet {
    
    private final AIService aiService = new AIServiceImpl();
    private final Gson gson = new Gson();
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (!isAdmin(request)) {
                result.put("success", false);
                result.put("message", "Access denied");
                out.print(gson.toJson(result));
                return;
            }
            
            String action = request.getParameter("action");
            
            if (action == null) {
                result.put("success", false);
                result.put("message", "Action parameter required");
                out.print(gson.toJson(result));
                return;
            }
            
            switch (action) {
                case "add":
                    handleAddModel(request, result);
                    break;
                case "update":
                    handleUpdateModel(request, result);
                    break;
                case "delete":
                    handleDeleteModel(request, result);
                    break;
                case "toggle":
                    handleToggleModel(request, result);
                    break;
                default:
                    result.put("success", false);
                    result.put("message", "Unsupported action");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "Internal server error: " + e.getMessage());
        }
        
        out.print(gson.toJson(result));
        out.flush();
        out.close();
    }
    
    private void handleAddModel(HttpServletRequest request, Map<String, Object> result) throws IOException {
        StringBuilder jsonBuilder = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        
        JsonObject requestJson = JsonParser.parseString(jsonBuilder.toString()).getAsJsonObject();
        
        String name = requestJson.get("name").getAsString();
        String description = requestJson.has("description") ? requestJson.get("description").getAsString() : "";
        String apiUrl = requestJson.get("apiUrl").getAsString();
        String apiKey = requestJson.get("apiKey").getAsString();
        int maxTokens = requestJson.has("maxTokens") ? requestJson.get("maxTokens").getAsInt() : 2000;
        double temperature = requestJson.has("temperature") ? requestJson.get("temperature").getAsDouble() : 0.7;
        
        if (name == null || name.trim().isEmpty() || 
            apiUrl == null || apiUrl.trim().isEmpty() ||
            apiKey == null || apiKey.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "Name, API URL and API key are required");
            return;
        }
        
        AIModel model = new AIModel();
        model.setId(UUID.randomUUID().toString());
        model.setName(name.trim());
        model.setDescription(description.trim());
        model.setApiUrl(apiUrl.trim());
        model.setApiKey(apiKey.trim());
        model.setMaxTokens(maxTokens);
        model.setTemperature(temperature);
        model.setStatus(1);
        
        boolean success = aiService.addModel(model);
        
        if (success) {
            result.put("success", true);
            result.put("message", "AI model added successfully");
        } else {
            result.put("success", false);
            result.put("message", "Failed to add AI model");
        }
    }
    
    private void handleUpdateModel(HttpServletRequest request, Map<String, Object> result) throws IOException {
        StringBuilder jsonBuilder = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        
        JsonObject requestJson = JsonParser.parseString(jsonBuilder.toString()).getAsJsonObject();
        
        String id = requestJson.get("id").getAsString();
        String name = requestJson.get("name").getAsString();
        String description = requestJson.has("description") ? requestJson.get("description").getAsString() : "";
        String apiUrl = requestJson.get("apiUrl").getAsString();
        String apiKey = requestJson.get("apiKey").getAsString();
        int maxTokens = requestJson.has("maxTokens") ? requestJson.get("maxTokens").getAsInt() : 2000;
        double temperature = requestJson.has("temperature") ? requestJson.get("temperature").getAsDouble() : 0.7;
        
        if (id == null || id.trim().isEmpty() ||
            name == null || name.trim().isEmpty() || 
            apiUrl == null || apiUrl.trim().isEmpty() ||
            apiKey == null || apiKey.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "ID, name, API URL and API key are required");
            return;
        }
        
        AIModel model = new AIModel();
        model.setId(id.trim());
        model.setName(name.trim());
        model.setDescription(description.trim());
        model.setApiUrl(apiUrl.trim());
        model.setApiKey(apiKey.trim());
        model.setMaxTokens(maxTokens);
        model.setTemperature(temperature);
        
        boolean success = aiService.updateModel(model);
        
        if (success) {
            result.put("success", true);
            result.put("message", "AI model updated successfully");
        } else {
            result.put("success", false);
            result.put("message", "Failed to update AI model");
        }
    }
    
    private void handleDeleteModel(HttpServletRequest request, Map<String, Object> result) {
        String modelId = request.getParameter("modelId");
        
        if (modelId == null || modelId.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "Model ID is required");
            return;
        }
        
        boolean success = aiService.deleteModel(modelId.trim());
        
        if (success) {
            result.put("success", true);
            result.put("message", "AI model deleted successfully");
        } else {
            result.put("success", false);
            result.put("message", "Failed to delete AI model");
        }
    }
    
    private void handleToggleModel(HttpServletRequest request, Map<String, Object> result) {
        String modelId = request.getParameter("modelId");
        
        if (modelId == null || modelId.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "Model ID is required");
            return;
        }
        
        boolean success = aiService.toggleModelStatus(modelId.trim());
        
        if (success) {
            result.put("success", true);
            result.put("message", "Model status toggled successfully");
        } else {
            result.put("success", false);
            result.put("message", "Failed to toggle model status");
        }
    }
    
    private boolean isAdmin(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) return false;
        
        User user = (User) session.getAttribute("user");
        return user != null && user.getRole() == 2;
    }
}